<?php

/**
 * Prevent warnings of resubmitting posted forms, save form data, seed forms with a random token for recognition and to reduce cross site scripting.
 * @author antz
 * @package  jfx-core-classes
 */


global $Antz_IntelliForm_hasrun;
$Antz_IntelliForm_hasrun = 0;

/**
 * Prevent warnings of resubmitting posted forms, save form data, seed forms with a random token for recognition and to reduce cross site scripting.
 * @author antz
 * @package  jfx-core-classes
 */
class Antz_IntelliForm
{

    /**
     * how long are forms kept for ( seconds )
     * @static int $expireTime
     */
    const expireTime = 300;

    /**
     * Save form contents for later restoration
     *
     * @param string $key
     * @param int $expire (seconds)
     */
    public static function save($key, $expire='')
    {
        $expire = ($expire=='') ? (constant('Antz_IntelliForm::expireTime') + time()) : ($expire+time());
        if(!isset($_SESSION['intelliForm'])||!is_array($_SESSION['intelliForm']))$_SESSION['intelliForm'] = array();
        $_SESSION['intelliForm'][$key] = $_POST;
        $_SESSION['intelliForm'][$key]['intelliFormExpires'] = $expire;
    }


    /**
     * Restore form contents from a previous save
     *
     * @param string $key
     */
    public static function restore($key)
    {
        $_POST = (isset($_SESSION['intelliForm'][$key])) ? $_SESSION['intelliForm'][$key] : array();
    }


    /**
     * Clear a saved form
     *
     * @param string $key
     */
    public static function clear($key)
    {
        if(isset($_SESSION['intelliForm'][$key])) unset($_SESSION['intelliForm'][$key]);
    }


    /**
     * clear all expired saves
     *
     */
    public static function purge()
    {
        if(isset($_SESSION['intelliForm']) && is_array($_SESSION['intelliForm'])){
            foreach($_SESSION['intelliForm'] as $key => $post){
                if($post['intelliFormExpires'] <= time()){
                    unset($_SESSION['intelliForm'][$key]);
                };
            };
        };
        // clear form seeds ( max 15 forms per page)
        while(isset($_SESSION['antzSeed']) && count($_SESSION['antzSeed']) > 15){
            unset($_SESSION['antzSeed'][0]);
            $_SESSION['antzSeed'] = array_regenerate_keys($_SESSION['antzSeed']);
        };
    }


    /**
     * Call this before doing anything else, to bypass the pesty confirm prompt
     * that appears when resubmitting post content
     *
     */
    public static function antiRepost()
    {
        global $Antz_IntelliForm_hasrun, $CONFIG;

        // just in case the function gets called twice in one page load, we would get a bad loop happening!
        if($Antz_IntelliForm_hasrun>0) return;
        else $Antz_IntelliForm_hasrun++;

        if(isset($_POST['antzSeed'])){
            // form has been submitted
            $_SESSION['post'] = $_POST;

            // move the files to a new temp location
            foreach($_FILES as $k => $file){
                $suffix = rand(0,999);
                if($file['tmp_name']=='') continue;
                rename($file['tmp_name'], $CONFIG->tmpDir.'/'.$suffix.$file['name']);
                //echo $file['tmp_name'].'<br />';
                $_FILES[$k]['tmp_name'] = $CONFIG->tmpDir.'/'.$suffix.$file['name'];
                chmod($CONFIG->tmpDir.'/'.$suffix.$file['name'], 0777);
            };

            $_SESSION['files']=$_FILES;

            // work out the requested page and redirect to it
            header('location:'.THIS_PAGE_URL);

            die('<script>window.location="'.THIS_PAGE_URL.'"</script>
            <a href="'.THIS_PAGE_URL.'">Continue >></a>');

        }elseif(isset($_SESSION['post'])){
            $_POST = $_SESSION['post'];
            $_FILES = $_SESSION['files'];
            $_REQUEST = array_merge($_REQUEST, $_POST);
            unset($_SESSION['post']);
        };
    }


    /**
     * Checks to see if the form has been submitted with a valid seed
     *
     * @param string $id namespace
     * @param bool $del delete the seed
     * @return bool $isSubmitted
     */
    public static function submitted($id='default', $del=true)
    {
        if(!isset($_POST['antzSeed'])){return false;};

        $seed = $_POST['antzSeed'];
        if(!isset($_SESSION['antzSeed'])||!is_array($_SESSION['antzSeed'])){$_SESSION['antzSeed']=array();};
		if(!is_array($_SESSION['antzSeed'][$id])) $_SESSION['antzSeed'][$id] = array();

        if(in_array($seed, $_SESSION['antzSeed'][$id])){
            $tmp = array_flip($_SESSION['antzSeed'][$id]);
            if($del) $_SESSION['antzSeed'][$id][$tmp[$seed]]=mt_rand(0,99999999);
            unset($tmp, $seed);
            return true;
        }else{
            return false;
        };
    }

    /**
     * Plant a seed to ensure forms are accepted by a verified session.
     * Check with Antz_IntelliForm::submitted()
     * @param string $id
     * @return string $htmlHiddenInputAsText
     */
    public static function seed($id='default')
    {
        $seed = mt_rand(0,99999999);
        if(!isset($_SESSION['antzSeed'])||!is_array($_SESSION['antzSeed'])){$_SESSION['antzSeed']=array();};
        if(!isset($_SESSION['antzSeed'][$id]) || !is_array($_SESSION['antzSeed'][$id])) $_SESSION['antzSeed'][$id] = array();
        $_SESSION['antzSeed'][$id][]=$seed;
        return '<div style="display: none"><input type="hidden" name="antzSeed" value="'.$seed.'" /></div>';
    }



}
